package es.castorm.business.customer.internal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.mysema.query.BooleanBuilder;

import es.castorm.arch.data.Dao;
import es.castorm.business.customer.CustomerCriteriaDTO;

@Dao
class CustomerDaoImpl implements CustomerDao {

	@Autowired
	CustomerRepository customerRepository;

	QCustomer customer = QCustomer.customer;

	public Customer find(Long id) {
		return customerRepository.findOne(id);
	}

	public Customer save(Customer customer) {
		return customerRepository.save(customer);
	}

	public void delete(Customer customer) {
		customerRepository.delete(customer);
	}

	public Iterable<Customer> find(CustomerCriteriaDTO criteria) {
		BooleanBuilder builder = new BooleanBuilder();
		if (StringUtils.hasText(criteria.getFirstname())) {
			builder.and(customer.firstname.eq(criteria.getFirstname()));
		}
		if (StringUtils.hasText(criteria.getLastname())) {
			builder.and(customer.lastname.eq(criteria.getLastname()));
		}
		if (StringUtils.hasText(criteria.getEmail())) {
			builder.and(customer.email.eq(criteria.getEmail()));
		}
		return customerRepository.findAll(builder.getValue());
	}
}
